<?php
/**
 * @authors alex (20779512@qq.com)
 * @date    2014-03-24 17:25:39
 * @version 1.0
 */

class BxpayAction extends BaseAction {

    public function index(){
        import('@.ORG.Weixinpay.WxPayPubHelper');
        //使用jsapi接口
        $jsApi = new JsApi_pub(C('APP_ID'),C('mch_id'),C('mch_key'),C('APP_SECRET'));

        //=========步骤1：网页授权获取用户openid============
        //通过code获得openid
        if (!isset($_GET['code'])){
            //触发微信返回code码
            $url = $jsApi->createOauthUrlForCode(urlencode(C('site_url').'/wxpay/index.php?g=Wap&m=Bxpay&a=index&price='.$_GET['price'].'&orderName='.urlencode($_GET['single_orderid']).'&single_orderid='.$_GET['single_orderid'].'&showwxpaytitle=1'));
             Header("Location: $url"); exit();
        }

        //获取code码，以获取openid
        $code = $_GET['code'];
        $jsApi->setCode($code);
        $openid = $jsApi->getOpenId();
        
        //获取订单信息
        $orderid=$_GET['single_orderid'];
        $map['bx_no'] = $orderid;
        $list = M('Baoxian')->where($map)->find(); 
        if (!$list) {
            echo 'error';die;
        }else{
            M('Baoxian')->where($map)->setField('payType',2);
            $price = $list['money'];
        }
        //判断是否已经支付过

        //=========步骤2：使用统一支付接口，获取prepay_id============
        //使用统一支付接口
        $unifiedOrder = new UnifiedOrder_pub(C('APP_ID'),C('mch_id'),C('mch_key'),C('APP_SECRET'));    
        $unifiedOrder->setParameter("openid",$openid);//商品描述
        $unifiedOrder->setParameter("body",C('site_name'));//商品描述
        //自定义订单号，此处仅作举例
        $unifiedOrder->setParameter("out_trade_no",$orderid);//商户订单号 
        $unifiedOrder->setParameter("total_fee",$price*100);//总金额
        //$unifiedOrder->setParameter("total_fee",'1');//总金额
        $unifiedOrder->setParameter("notify_url",C('site_url').'/wxpay/bxnotice.php');//通知地址 
        $unifiedOrder->setParameter("trade_type","JSAPI");//交易类型

        $prepay_id = $unifiedOrder->getPrepayId();

        //=========步骤3：使用jsapi调起支付============
        $jsApi->setPrepayId($prepay_id);
        $jsApiParameters = $jsApi->getParameters();
        $this->assign('jsApiParameters',$jsApiParameters);
        $this->assign('price',floatval($price));                

        $returnUrl = C('site_url').'/index.php?g=Wap&m=Bxpayreturn&a=index&order_no='.$orderid;
        $this->assign('returnUrl',$returnUrl);
        $this->display();
    }   

}